package com.agileai.portal.controller.base;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.map.ObjectMapper;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.auth.SecurityGroupManage;
import com.agileai.portal.driver.AttributeKeys;
import com.agileai.portal.driver.model.MenuBar;
import com.agileai.portal.driver.model.MenuItem;
import com.agileai.portal.driver.model.PersonalFavorite;
import com.agileai.portal.driver.service.DriverConfiguration;
import com.agileai.portal.driver.service.PortalConfigService;
import com.agileai.portal.filter.UserCacheManager;
import com.agileai.util.ListUtil;

public class PersonalFavoriteConfigHandler extends BaseHandler{

	public PersonalFavoriteConfigHandler(){
		super();
	}
	
	private PortalConfigService getPortalConfigService(){
		ServletContext servletContext = this.dispatchServlet.getServletContext();
		DriverConfiguration driverConfiguration = (DriverConfiguration)servletContext.getAttribute(AttributeKeys.DRIVER_CONFIG);
		return driverConfiguration.getPortalConfigService();
	}
	
	public ViewRenderer prepareDisplay(DataParam param) {
		String currMenuItemId = param.get("menuItemId");
		String navId = param.get("navId");
		User user = (User)this.getUser();
		PersonalFavorite personalSetting = (PersonalFavorite)user.getExtendProperties().get(AttributeKeys.PERSONAL_FAVORITE_OBJECT_KEY);
		List<String> favoritePages = personalSetting.getFavoritePages(navId);
		List<DataRow> records = new ArrayList<DataRow>();
		List<String> invalidfavoriteIdList = new ArrayList<String>();
		
		for (int i=0;i < favoritePages.size();i++){
			String favoriteId = favoritePages.get(i); 
			String[] temp = favoriteId.split("/");
			String menuBarId = temp[0];
			String menuItemId = temp[1];
			String currentMenuId = null;
			if (temp.length > 2){
				currentMenuId = temp[2];
			}
			MenuBar menuBar = getPortalConfigService().getMenuBar(menuBarId);
			if (menuBar == null){
				invalidfavoriteIdList.add(favoriteId);
				continue;
			}
			MenuItem menuItem = menuBar.getMenuItemIdMap().get(menuItemId);
			if (menuItem == null){
				invalidfavoriteIdList.add(favoriteId);
				continue;
			}
			String title = menuItem.getName();
			
			if (currentMenuId != null){
				HttpSession session = request.getSession();
				HashMap<String,org.codehaus.jettison.json.JSONObject> menuJSONObjectMap = (HashMap<String,org.codehaus.jettison.json.JSONObject>)MenuBar.getMenuJSONObjectMap(session);
				org.codehaus.jettison.json.JSONObject jsonObject = menuJSONObjectMap.get(currentMenuId);
				try {
					title = jsonObject.getString("text");					
				} catch (Exception e) {
					this.log.error(e.getLocalizedMessage(), e);
				}
			}
			DataRow row = new DataRow();
			row.put("favoriteId",favoriteId);
			row.put("favoriteTitle",title);
			records.add(row);
		}
		if (invalidfavoriteIdList.size() > 0){
			favoritePages.removeAll(invalidfavoriteIdList);			
		}
		this.setRsList(records);
		this.setAttribute("menuItemId", currMenuItemId);
		this.setAttribute("navId", navId);
		return new LocalRenderer(getPage());
	}
	
	@PageAction
	public ViewRenderer saveSortedFavorites(DataParam param){
		String rspText = FAIL;
		String favoriteIds = param.get("favoriteIds");
		String navId = param.get("navId");
		User user = (User)this.getUser();
		
		SecurityGroupManage securityGroupManage = this.lookupService(SecurityGroupManage.class);
		PersonalFavorite personalFavorite = (PersonalFavorite)user.getExtendProperties().get(AttributeKeys.PERSONAL_FAVORITE_OBJECT_KEY);
		List<String> favoritePages = personalFavorite.getFavoritePages(navId);
		favoritePages.clear();
		ListUtil.addArrayToList(favoritePages, favoriteIds.split(","));
		String userCode = user.getUserCode();
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			String jsonString = objectMapper.writeValueAsString(personalFavorite);
			securityGroupManage.updateSecurityUserFavorites(userCode, jsonString);
			
			UserCacheManager userCacheManager = UserCacheManager.getOnly();
			userCacheManager.removeUser(userCode);
			rspText = SUCCESS;			
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(rspText);
	}

	@PageAction
	public ViewRenderer deleteFavorite(DataParam param){
		String responseText = FAIL;
		try {
			String navId = param.get("navId");
			String favoriteId = param.get("favoriteId");
			User user = (User)this.getUser();
			SecurityGroupManage securityGroupManage = this.lookupService(SecurityGroupManage.class);
			PersonalFavorite personalFavorite = (PersonalFavorite)user.getExtendProperties().get(AttributeKeys.PERSONAL_FAVORITE_OBJECT_KEY);
			List<String> favoritePages = personalFavorite.getFavoritePages(navId);
			favoritePages.remove(favoriteId);
			
			String userCode = user.getUserCode();
			ObjectMapper objectMapper = new ObjectMapper();
			String jsonString = objectMapper.writeValueAsString(personalFavorite);
			securityGroupManage.updateSecurityUserFavorites(userCode, jsonString);
			
			UserCacheManager userCacheManager = UserCacheManager.getOnly();
			userCacheManager.removeUser(userCode);
			
			responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
}